<template>
  <div class="table-box">
    <!-- 搜索表单 -->
    <el-form :model="searchForm" ref="searchFormRef" :inline="true" class="search-form">
      <el-form-item label="产品编码" prop="productCode">
        <el-input v-model="searchForm.productCode" placeholder="请输入产品编码" clearable />
      </el-form-item>
      <el-form-item label="产品名称" prop="productName">
        <el-input v-model="searchForm.productName" placeholder="请输入产品名称" clearable />
      </el-form-item>
      <el-form-item label="产品状态" prop="status">
        <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 180px">
          <el-option label="已创建" value="created" />
          <el-option label="已启用" value="enabled" />
          <el-option label="已禁用" value="disabled" />
          <el-option label="已审核" value="approved" />
          <el-option label="已驳回" value="rejected" />
          <el-option label="已删除" value="deleted" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <div class="table-header">
      <el-button type="primary" :icon="CirclePlus" @click="handleAdd">新增产品</el-button>
    </div>

    <el-table :data="tableData" style="width: 100%" v-loading="loading" border>
      <el-table-column type="index" label="序号" min-width="60" />
      <el-table-column prop="productCode" label="产品编码" min-width="120" />
      <el-table-column prop="productName" label="产品名称" min-width="150" />
      <el-table-column prop="model" label="产品型号" min-width="120" />
      <el-table-column prop="category" label="产品类别" wimin-widthdth="100" />
      <el-table-column prop="type" label="产品类型" min-width="100">
        <template #default="scope">
          <el-tag :type="getTypeTagType(scope.row.type)" size="small">{{ getTypeText(scope.row.type) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="specification" label="规格" show-overflow-tooltip width="200" />
      <el-table-column prop="version" label="版本号" min-width="80" />
      <el-table-column prop="unit" label="单位" min-width="80" />
      <el-table-column prop="status" label="产品状态" min-width="100">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createdTime" label="创建时间" min-width="150" />
      <el-table-column label="操作" min-width="400" fixed="right">
        <template #default="scope">
          <el-button type="primary" link :icon="View" @click="handleView(scope.row)" class="operation-btn">查看</el-button>
          <el-button type="primary" link :icon="EditPen" @click="handleEdit(scope.row)" class="operation-btn">编辑</el-button>
          <el-button type="danger" link @click="handleDelete(scope.row)" class="operation-btn">删除</el-button>

          <!-- 更多操作下拉菜单 -->
          <el-dropdown @command="handleMoreAction" trigger="click">
            <el-button type="primary" link class="operation-btn">
              更多 <el-icon class="el-icon--right"><arrow-down /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item :command="{ action: 'enable', row: scope.row }">
                  <el-icon><check /></el-icon>
                  启用
                </el-dropdown-item>
                <el-dropdown-item :command="{ action: 'disable', row: scope.row }">
                  <el-icon><close /></el-icon>
                  禁用
                </el-dropdown-item>
                <el-dropdown-item :command="{ action: 'changeVersion', row: scope.row }">
                  <el-icon><edit /></el-icon>
                  变更版本
                </el-dropdown-item>
                <el-dropdown-item :command="{ action: 'updateBOM', row: scope.row }">
                  <el-icon><document /></el-icon>
                  更新BOM
                </el-dropdown-item>
                <el-dropdown-item :command="{ action: 'assignRoute', row: scope.row }">
                  <el-icon><link /></el-icon>
                  分配工艺路线
                </el-dropdown-item>
                <el-dropdown-item :command="{ action: 'approve', row: scope.row }">
                  <el-icon><select /></el-icon>
                  审核通过
                </el-dropdown-item>
                <el-dropdown-item :command="{ action: 'reject', row: scope.row }">
                  <el-icon><close /></el-icon>
                  审核驳回
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        :current-page="pagination.currentPage"
        :page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes, prev, pager, next, jumper"
      />
    </div>

    <!-- 产品表单抽屉 -->
    <ProductForm ref="formDrawerRef" />

    <!-- 变更版本对话框 -->
    <el-dialog v-model="versionDialogVisible" title="变更产品版本" width="400px">
      <el-form :model="versionForm" ref="versionFormRef" :rules="versionRules" label-width="100px">
        <el-form-item label="新版本号" prop="newVersion">
          <el-input v-model="versionForm.newVersion" placeholder="请输入新版本号" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="versionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleVersionConfirm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 分配工艺路线对话框 -->
    <el-dialog v-model="routeDialogVisible" title="分配工艺路线" width="400px">
      <el-form :model="routeForm" ref="routeFormRef" :rules="routeRules" label-width="100px">
        <el-form-item label="工艺路线" prop="routeId">
          <el-select v-model="routeForm.routeId" placeholder="请选择工艺路线" style="width: 100%">
            <el-option
              v-for="route in routeOptions"
              :key="route.id"
              :label="route.routeName"
              :value="route.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="routeDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleRouteConfirm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 审核驳回对话框 -->
    <el-dialog v-model="rejectDialogVisible" title="审核驳回" width="400px">
      <el-form :model="rejectForm" ref="rejectFormRef" :rules="rejectRules" label-width="100px">
        <el-form-item label="驳回原因" prop="reason">
          <el-input
            v-model="rejectForm.reason"
            type="textarea"
            :rows="4"
            placeholder="请输入驳回原因"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="rejectDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleRejectConfirm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="productTable">
import { ref, reactive, onMounted } from "vue";
import type { FormInstance } from "element-plus";
import { ElMessage, ElMessageBox } from "element-plus";
import { CirclePlus, EditPen, View, ArrowDown, Check, Close, Edit, Document, Link, Select } from "@element-plus/icons-vue";
import ProductForm from "./form.vue";
import { PageHelper } from "@/utils/pageHelper";
import {
  getProductList,
  enableProduct,
  disableProduct,
  deleteProduct,
  changeProductVersion,
  updateProductBOM,
  assignProductRoute,
  approveProduct,
  rejectProduct,
  type Product
} from "@/api/modules/product";
import { getRouteList } from "@/api/modules/route";

const loading = ref(false);
const tableData = ref<Product.ProductListItem[]>([]);
const searchFormRef = ref<FormInstance>();

// 查询表单
const searchForm = reactive({
  productCode: "",
  productName: "",
  status: ""
});

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 版本变更对话框
const versionDialogVisible = ref(false);
const versionFormRef = ref<FormInstance>();
const versionForm = reactive({
  newVersion: ""
});
const versionRules = {
  newVersion: [{ required: true, message: "请输入新版本号", trigger: "blur" }]
};
const currentVersionRow = ref<Product.ProductListItem | null>(null);

// 分配工艺路线对话框
const routeDialogVisible = ref(false);
const routeFormRef = ref<FormInstance>();
const routeForm = reactive({
  routeId: null as number | null
});
const routeRules = {
  routeId: [{ required: true, message: "请选择工艺路线", trigger: "change" }]
};
const routeOptions = ref<any[]>([]);
const currentRouteRow = ref<Product.ProductListItem | null>(null);

// 审核驳回对话框
const rejectDialogVisible = ref(false);
const rejectFormRef = ref<FormInstance>();
const rejectForm = reactive({
  reason: ""
});
const rejectRules = {
  reason: [{ required: true, message: "请输入驳回原因", trigger: "blur" }]
};
const currentRejectRow = ref<Product.ProductListItem | null>(null);

// 获取状态类型
const getStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    created: "info",
    enabled: "success",
    disabled: "warning",
    approved: "primary",
    rejected: "danger",
    deleted: "info"
  };
  return statusMap[status] || "info";
};

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    created: "已创建",
    enabled: "已启用",
    disabled: "已禁用",
    approved: "已审核",
    rejected: "已驳回",
    deleted: "已删除"
  };
  return statusMap[status] || status;
};

// 获取产品类型标签类型
const getTypeTagType = (type: string) => {
  const typeMap: Record<string, string> = {
    RAW_MATERIAL: "info",
    SEMI_FINISHED: "warning", 
    FINISHED: "success"
  };
  return typeMap[type] || "info";
};

// 获取产品类型文本
const getTypeText = (type: string) => {
  const typeMap: Record<string, string> = {
    RAW_MATERIAL: "原材料",
    SEMI_FINISHED: "半成品",
    FINISHED: "成品"
  };
  return typeMap[type] || type;
};

// 获取表格数据
const getTableData = async () => {
  loading.value = true;
  try {
    const params = PageHelper.createPageParams(pagination.currentPage, pagination.pageSize, searchForm);
    const res = await getProductList(params);

    // 使用PageHelper安全解析分页数据
    const pageData = PageHelper.parsePage<Product.ProductListItem>(res.data);
    tableData.value = pageData.records;
    pagination.total = pageData.total;

    console.log("解析后的分页数据:", pageData);
  } catch (error) {
    console.error("获取产品列表失败:", error);
    ElMessage.error("获取产品列表失败");
  } finally {
    loading.value = false;
  }
};

// 获取工艺路线选项
const getRouteOptions = async () => {
  try {
    const res = await getRouteList({ current: 1, size: 1000 });
    const pageData = PageHelper.parsePage(res.data);
    routeOptions.value = pageData.records;
  } catch (error) {
    console.error("获取工艺路线列表失败:", error);
  }
};

// 查询
const handleSearch = () => {
  pagination.currentPage = 1;
  getTableData();
};

// 重置
const handleReset = () => {
  if (!searchFormRef.value) return;
  searchFormRef.value.resetFields();
  pagination.currentPage = 1;
  getTableData();
};

// 分页大小改变
const handleSizeChange = (val: number) => {
  pagination.pageSize = val;
  getTableData();
};

// 当前页改变
const handleCurrentChange = (val: number) => {
  pagination.currentPage = val;
  getTableData();
};

// 产品表单抽屉引用
const formDrawerRef = ref<InstanceType<typeof ProductForm>>();

// 新增产品
const handleAdd = () => {
  const params = {
    title: "新增",
    isView: false,
    row: {},
    getTableList: getTableData
  };
  formDrawerRef.value?.open(params);
};

const handleView = (row: Product.ProductListItem) => {
  const params = {
    title: "查看",
    isView: true,
    row: { ...row },
    getTableList: getTableData
  };
  formDrawerRef.value?.open(params);
};

// 编辑产品
const handleEdit = (row: Product.ProductListItem) => {
  const params = {
    title: "编辑",
    isView: false,
    row: { ...row },
    getTableList: getTableData
  };
  formDrawerRef.value?.open(params);
};

// 启用产品
const handleEnable = async (row: Product.ProductListItem) => {
  try {
    await enableProduct(row.id);
    ElMessage.success("产品启用成功");
    getTableData();
  } catch (error) {
    console.error("产品启用失败:", error);
    ElMessage.error("产品启用失败");
  }
};

// 禁用产品
const handleDisable = async (row: Product.ProductListItem) => {
  try {
    await disableProduct(row.id);
    ElMessage.success("产品禁用成功");
    getTableData();
  } catch (error) {
    console.error("产品禁用失败:", error);
    ElMessage.error("产品禁用失败");
  }
};

// 删除产品
const handleDelete = async (row: Product.ProductListItem) => {
  ElMessageBox.confirm(`确认删除产品 "${row.productName}" 吗？`, "删除确认", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      try {
        await deleteProduct(row.id);
        ElMessage.success("产品删除成功");
        getTableData();
      } catch (error) {
        console.error("产品删除失败:", error);
        ElMessage.error("产品删除失败");
      }
    })
    .catch(() => {
      // 取消删除
    });
};

// 变更版本
const handleChangeVersion = (row: Product.ProductListItem) => {
  currentVersionRow.value = row;
  versionForm.newVersion = "";
  versionDialogVisible.value = true;
};

// 确认变更版本
const handleVersionConfirm = async () => {
  if (!versionFormRef.value || !currentVersionRow.value) return;

  await versionFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await changeProductVersion(currentVersionRow.value!.id, {
          newVersion: versionForm.newVersion
        });
        ElMessage.success("版本变更成功");
        versionDialogVisible.value = false;
        getTableData();
      } catch (error) {
        console.error("版本变更失败:", error);
        ElMessage.error("版本变更失败");
      }
    }
  });
};

// 更新BOM
const handleUpdateBOM = async (row: Product.ProductListItem) => {
  try {
    await updateProductBOM(row.id);
    ElMessage.success("BOM更新成功");
    getTableData();
  } catch (error) {
    console.error("BOM更新失败:", error);
    ElMessage.error("BOM更新失败");
  }
};

// 分配工艺路线
const handleAssignRoute = (row: Product.ProductListItem) => {
  currentRouteRow.value = row;
  routeForm.routeId = null;
  routeDialogVisible.value = true;
  getRouteOptions();
};

// 确认分配工艺路线
const handleRouteConfirm = async () => {
  if (!routeFormRef.value || !currentRouteRow.value) return;

  await routeFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await assignProductRoute(currentRouteRow.value!.id, {
          routeId: routeForm.routeId!
        });
        ElMessage.success("工艺路线分配成功");
        routeDialogVisible.value = false;
        getTableData();
      } catch (error) {
        console.error("工艺路线分配失败:", error);
        ElMessage.error("工艺路线分配失败");
      }
    }
  });
};

// 审核通过
const handleApprove = async (row: Product.ProductListItem) => {
  ElMessageBox.confirm(`确认审核通过产品 "${row.productName}" 吗？`, "审核确认", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      try {
        await approveProduct(row.id);
        ElMessage.success("产品审核通过");
        getTableData();
      } catch (error) {
        console.error("产品审核失败:", error);
        ElMessage.error("产品审核失败");
      }
    })
    .catch(() => {
      // 取消审核
    });
};

// 审核驳回
const handleReject = (row: Product.ProductListItem) => {
  currentRejectRow.value = row;
  rejectForm.reason = "";
  rejectDialogVisible.value = true;
};

// 确认审核驳回
const handleRejectConfirm = async () => {
  if (!rejectFormRef.value || !currentRejectRow.value) return;

  await rejectFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await rejectProduct(currentRejectRow.value!.id, {
          reason: rejectForm.reason
        });
        ElMessage.success("产品审核驳回");
        rejectDialogVisible.value = false;
        getTableData();
      } catch (error) {
        console.error("产品审核驳回失败:", error);
        ElMessage.error("产品审核驳回失败");
      }
    }
  });
};

// 处理更多操作下拉菜单
const handleMoreAction = (command: { action: string; row: Product.ProductListItem }) => {
  const { action, row } = command;

  switch (action) {
    case "enable":
      handleEnable(row);
      break;
    case "disable":
      handleDisable(row);
      break;
    case "changeVersion":
      handleChangeVersion(row);
      break;
    case "updateBOM":
      handleUpdateBOM(row);
      break;
    case "assignRoute":
      handleAssignRoute(row);
      break;
    case "approve":
      handleApprove(row);
      break;
    case "reject":
      handleReject(row);
      break;
    default:
      console.warn("未知的操作类型:", action);
  }
};

// 页面加载时获取数据
onMounted(() => {
  getTableData();
});
</script>

<style scoped>
.search-form {
  background-color: #fff;
  padding: 10px;
  border-radius: 4px;
  margin-bottom: 16px;
}

.table-header {
  margin-bottom: 16px;
  display: flex;
  gap: 10px;
}

.el-table {
  flex: 1;
}

:deep(.el-table__row) {
  height: 30px !important;
  line-height: 35px;
}

:deep(.el-table__cell) {
  padding: 12px 0;
}

:deep(.el-table__header-row) {
  height: 65px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  flex-shrink: 0;
}

:deep(.operation-btn) {
  font-size: 14px;
  margin: 0 2px;
}

:deep(.operation-btn .el-icon) {
  font-size: 16px;
  margin-right: 2px;
}
</style>